<?php
namespace Icsoc\UIBundle\Twig\Extension;


use Icsoc\UIBundle\Breadcrumb\Breadcrumb;
use Symfony\Component\DependencyInjection\ContainerInterface;

/**
 * @author Wenming Tang <tang@babyfamily.com>
 */
class BreadcrumbExtension extends \Twig_Extension
{
    /**
     * @var ContainerInterface
     */
    protected $container;

    /**
     * @var Breadcrumb
     */
    protected $breadcrumb;

    /**
     * @param ContainerInterface  $container
     * @param Breadcrumb $breadcrumb
     */
    public function __construct(ContainerInterface $container, Breadcrumb $breadcrumb)
    {
        $this->container  = $container;
        $this->breadcrumb = $breadcrumb;
    }

    /**
     * @return array
     */
    public function getFunctions()
    {
        return array(
            'breadcrumbs'        => new \Twig_Function_Method($this, 'breadcrumbs', array("is_safe" => array("html"))),
            'render_breadcrumbs' => new \Twig_Function_Method($this, 'renderBreadcrumbs', array("is_safe" => array("html"))),
            'page_title'         => new \Twig_Function_Method($this, 'pageTitle', array("is_safe" => array("html")))
        );
    }

    /**
     * @return array
     */
    public function breadcrumbs()
    {
        return $this->breadcrumb->getBreadcrumbs();
    }

    /**
     * @return string
     */
    public function renderBreadcrumbs()
    {
        return $this->container->get('templating')->render('IcsocUIBundle:Breadcrumb:breadcrumb.html.twig', array(
            'breadcrumbs' => $this->breadcrumbs()
        ));
    }

    /**
     * @return array
     */
    public function pageTitle()
    {
        $breadcrumbs = $this->breadcrumbs();
        $last_crumb  = end($breadcrumbs);

        return $last_crumb->getText();
    }

    /**
     * @return string
     */
    public function getName()
    {
        return 'icsoc.breadcrumb';
    }
}
